//
//  ZCCommentViewController.m
//  百思不得姐
//
//  Created by Ning Xie on 16/9/2.
//  Copyright © 2016年 zhangchong. All rights reserved.
//

#import "ZCCommentViewController.h"
#import "ZCCommentCell.h"
#import "ZCEssenceCell.h"
#import "ZCEssenceModel.h"
#import "ZCCommentModel.h"


#define commentEditViewHeight 40
#define commentEditViewButtonMargin 10
#define CommentCellIdentifier @"CommentCellIdentifier"


@interface ZCCommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>

@property (weak, nonatomic) UIView *commentEditView;    //底部编辑视图
@property (weak, nonatomic) UIButton *connectBtn;       //底部视图右侧@按钮

@property (weak, nonatomic) UIButton *voiceBtn;         //语音按钮
@property (weak, nonatomic) UIButton *voiceInputBtn;    //发送语音
@property (weak, nonatomic) UIButton *editBtn;          //键盘按钮
@property (weak, nonatomic) UITextView *editInputView;  //文字输入

@property (weak, nonatomic) UITableView *commentTableView;  //中间滚动视图

@property (strong, nonatomic) NSMutableArray *commentArray;
@property (strong, nonatomic) NSArray *hotCommentArray;

@property (copy, nonatomic) NSString *total;
@property (copy, nonatomic) NSString *lastcid;
@property (assign, nonatomic) NSInteger page;




@end

@implementation ZCCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self setupUI];
    [self setupCommentVoiceView];
    [self.commentTableView.mj_header beginRefreshing];
}

-(NSMutableArray *)commentArray{
    if (!_commentArray) {
        _commentArray = [NSMutableArray array];
    }
    return _commentArray;
}
/**
 *  加载网络数据
 */
-(void)loadDataWithLastcid:(NSString*)lastcid page:(NSInteger)page{

//    [SVProgressHUD show];
    //        [SVProgressHUD dismiss];
    [[ZCNetworkingTools sharedNetWorkingTools] requestCommentWithdataID:self.model.ID lastcid:lastcid page:page callBack:^(NSDictionary *response, NSError *error) {
        
        if (error != nil) {
            ZCLog(@"数据请求错误 %@",error);
            
            [self.commentTableView.mj_footer endRefreshing];
            [self.commentTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:@"数据加载失败"];
            return ;
        }
        if (![response isKindOfClass:[NSDictionary class]]) {
            ZCLog(@"不是一个合法的字典");
            
            [self.commentTableView.mj_footer endRefreshing];
            [self.commentTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:@"数据加载失败"];
            return;
        }
        
        self.total = response[@"total"];
        
        NSArray *dataArray = response[@"data"];
        NSArray *tempArray = [ZCCommentModel mj_objectArrayWithKeyValuesArray:dataArray];
        self.lastcid = dataArray.lastObject[@"id"];
        
        NSArray *hotArray = response[@"hot"];
        self.hotCommentArray = [ZCCommentModel mj_objectArrayWithKeyValuesArray:hotArray];
        
        if (self.commentTableView.mj_footer.isRefreshing) {
            
            [self.commentArray addObjectsFromArray:tempArray];
            
        }else{

            self.commentArray = [ZCCommentModel mj_objectArrayWithKeyValuesArray:dataArray];
        }
        
        
//        ZCLog(@"%@",response);
//        ZCLog(@"返回数据的评论数%ld",dataArray.count);
//        ZCLog(@"%@",dataArray);
//        ZCLog(@"热评数量%ld",hotArray.count);
//        ZCLog(@"评论总数%@",self.total);
//        ZCLog(@"评论加载数量%ld",self.commentArray.count);
//        ZCLog(@"最后一个评论ID%@",self.lastcid);
//        ZCLog(@"============================");
        
        [self.commentTableView reloadData];
        
        [self.commentTableView.mj_header endRefreshing];
        [self.commentTableView.mj_footer endRefreshing];
        
        if (!(self.commentArray.count < self.total.integerValue)) {
            [self.commentTableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        
    }];
    


}
/**
 *  布局页面
 */
-(void)setupUI{
    
    self.navigationItem.title = @"评论";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"comment_nav_item_share_icon" selectedImage:@"comment_nav_item_share_icon_click" action:nil target:self];

    
    UITableView *commentTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:commentTableView];
    self.commentTableView = commentTableView;
    
    
    commentTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(commentViewLoadMoreData)];
    commentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(commentViewLoadNewData)];
    commentTableView.mj_footer.hidden = YES;
    
    
    
    commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    commentTableView.rowHeight = UITableViewAutomaticDimension;
    commentTableView.estimatedRowHeight = 300;
    commentTableView.dataSource = self;
    commentTableView.delegate = self;
    [commentTableView registerClass:[ZCCommentCell class] forCellReuseIdentifier:CommentCellIdentifier];

    
    
    [commentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    
    UIView *commentEditView = [[UIView alloc]init];
    commentEditView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"comment-bar-bg"]];
    [self.view addSubview:commentEditView];
    self.commentEditView = commentEditView;
    [self.view bringSubviewToFront:commentEditView];
    
    [commentEditView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.width.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(commentEditViewHeight);
    }];
    
    UIButton *connectBtn = [UIButton buttonWithBackgroundImage:@"comment_bar_at_icon" highlightedImage:@"comment_bar_at_icon_click"];
    [commentEditView addSubview:connectBtn];
    self.connectBtn = connectBtn;
    
    [connectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(commentEditView).offset(-commentEditViewButtonMargin);
        make.centerY.equalTo(commentEditView);
        make.height.equalTo(commentEditView.mas_height).offset(-commentEditViewButtonMargin);
        make.width.equalTo(connectBtn.mas_height);
    }];
    
    
   
    
    
    
    
}
/**
 *  布局发送语音页面
 */
-(void)setupCommentVoiceView{
    
    self.editBtn.hidden = YES;
    self.editInputView.hidden = YES;
    
    UIButton *voiceBtn = [UIButton buttonWithBackgroundImage:@"comment-bar-voice" highlightedImage:@"comment-bar-voice-click"];
    [self.commentEditView addSubview:voiceBtn];
    self.voiceBtn = voiceBtn;
    
    [voiceBtn addTarget:self action:@selector(setupCommentEditView) forControlEvents:UIControlEventTouchUpInside];
    
    [voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.commentEditView).offset(commentEditViewButtonMargin);
        make.centerY.equalTo(self.commentEditView);
        make.width.height.equalTo(self.connectBtn);
    }];
    
    UIButton *voiceInputBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceInputBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
    [voiceInputBtn setTitle:@"松手 结束" forState:UIControlStateHighlighted];
    [voiceInputBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [voiceInputBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [voiceInputBtn setBackgroundImage:[UIImage imageNamed:@"comment-bar-record"] forState:UIControlStateNormal];
    [voiceInputBtn setBackgroundImage:[UIImage imageNamed:@"comment-bar-record-click"] forState:UIControlStateHighlighted];
    [self.commentEditView addSubview:voiceInputBtn];
    self.voiceInputBtn = voiceInputBtn;
    
    [voiceInputBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.commentEditView);
        make.leading.equalTo(voiceBtn.mas_trailing).offset(commentEditViewButtonMargin);
        make.trailing.equalTo(self.connectBtn.mas_leading).offset(-commentEditViewButtonMargin);
        make.height.equalTo(self.commentEditView).offset(-commentEditViewButtonMargin);
    }];
    [self.view endEditing:YES];
    
}
/**
 *  布局发送文字页面
 */
-(void)setupCommentEditView{
    self.voiceBtn.hidden = YES;
    self.voiceInputBtn.hidden = YES;
    
    UIButton *editBtn = [UIButton buttonWithBackgroundImage:@"comment-bar-keyboard" highlightedImage:@"comment-bar-keyboard-click"];
    [self.commentEditView addSubview:editBtn];
    self.editBtn = editBtn;
    
    [editBtn addTarget:self action:@selector(setupCommentVoiceView) forControlEvents:UIControlEventTouchUpInside];
    
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.commentEditView).offset(commentEditViewButtonMargin);
        make.centerY.equalTo(self.commentEditView);
        make.width.height.equalTo(self.connectBtn);
    }];
    
    UITextView *editInputView = [[UITextView alloc]init];
    [self.commentEditView addSubview:editInputView];
    editInputView.autocorrectionType = UITextAutocorrectionTypeNo;
    self.editInputView = editInputView;
    [editInputView becomeFirstResponder];
    
    [editInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.commentEditView);
        make.leading.equalTo(editBtn.mas_trailing).offset(commentEditViewButtonMargin);
        make.trailing.equalTo(self.connectBtn.mas_leading).offset(-commentEditViewButtonMargin);
        make.height.equalTo(self.commentEditView).offset(-commentEditViewButtonMargin);
    }];
    
}
/**
 *  监听键盘frame变化
 */
-(void)keyboardWillChangeFrame:(NSNotification*)noti{
    
    CGFloat duration = [noti.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    CGRect keyboardFrame = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    
    [self.commentEditView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(keyboardFrame.origin.y - self.view.height);
    }];
    
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}
/**
 *  上拉加载
 */
-(void)commentViewLoadMoreData{
    
    if (!(self.commentArray.count < self.total.integerValue)) {
        return;
    }
    
    if (self.commentTableView.mj_header.isRefreshing) {
        
        [self.commentTableView.mj_header endRefreshing];
    }
//    ZCLog(@"加载更多");
    NSString *lastcid = self.lastcid;
    [self loadDataWithLastcid:lastcid page: ++self.page];
}
/**
 *  下拉刷新
 */
-(void)commentViewLoadNewData{
    
    self.page = 1;
    if (self.commentTableView.mj_footer.isRefreshing) {
        
        [self.commentTableView.mj_footer endRefreshing];
    }
//    ZCLog(@"下拉刷新");
    [self loadDataWithLastcid:nil page:self.page];
}

#pragma mark - Tableview数据源方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    tableView.mj_footer.hidden = (self.commentArray.count == 0);
    
    return  self.hotCommentArray.count? 3:2;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView.numberOfSections == 3){
        switch (section) {
            case 0:
                return 1;
                break;
            case 1:
                return self.hotCommentArray.count;
                break;
            case 2:
                return self.commentArray.count;
                break;
            default:
                return 0;
        }
    }else
    {
        switch (section) {
            case 0:
                return 1;
                break;
            case 1:
                return self.commentArray.count;
                break;
            default:
                return 0;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    if (indexPath.section == 0) {
        
        ZCEssenceCell *cell = [[ZCEssenceCell alloc]init];
        self.model.top_cmt = nil;
        cell.model = self.model;
        
        return cell;
        
    }else if (indexPath.section == 1){
        
        ZCCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[ZCCommentCell alloc]init];
        }
        if (tableView.numberOfSections == 2) {
            cell.model = self.commentArray[indexPath.row];
        }else{
            cell.model = self.hotCommentArray[indexPath.row];
        }
        
        return cell;
    }else{
        
        ZCCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[ZCCommentCell alloc]init];
        }
        cell.model = self.commentArray[indexPath.row];
        return cell;
    }
    
    
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (section == 0) {
//        return 10;
//    }
    return 10;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (tableView.numberOfSections == 3){
        if (section == 1) {
            return @"最热评论";
        }else if (section == 2){
            return @"最新评论";
        }else{
            return nil;
        }
    }else{
        return (section != 1) ? @"": @"最新评论";
    }

}




@end
